var Echart = require('echarts/lib/echarts');
require('echarts/lib/chart/pie');
require('echarts/lib/chart/bar');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
Ajax = ZFT.Util.Ajax;

var Main = ZFT.Util.Class({
    init: function () {
        var _this = this;
        _this.initChart();
        $("#OperateS").on("click", function (e) {
            var tarTab = $(e.currentTarget);
            if (tarTab.hasClass("active")) return false;
            tarTab.addClass("active").siblings().removeClass("active");
            _this.initChart()
        })

    },
    initChart: function () {
        var _this = this;
        var dom = '<div id="chartPieBox"  class="u-box-chart"></div>' +
            '<div id="chartBarBox"  class="u-box-chart"></div>';
        $("#optBox").html(dom);
        _this.loadChartPie();
        _this.loadChartBar();
    },
    loadChartPie: function () {
        var _this = this,
            chartPieBox = document.getElementById('chartPieBox'),
            eChart = Echart.init(chartPieBox),
            option = null;
        Ajax("/r/UserCenter_houseStatistics", {
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 200) {
                    var data = _this.getData(res.data);
                    option = {
                        backgroundColor: '#2c343c',
                        title: {
                            text: '托管统计',
                            left: 'center',
                            top: 20,
                            textStyle: {
                                color: '#cc4c34'
                            }
                        },

                        tooltip: {
                            trigger: 'item',

                            formatter: "{a} <br/>{b}<br/> 总共 {c} ,占比({d}%)  <br/> "
                        },
                        /*legend: {
                            orient: 'vertical',
                            x: 'left',
                            textStyle: {
                                color: 'rgba(255, 233, 255, 0.8)'
                            },
                            data: ['未出租数量', '已出租数量', '今日到期']
                        },*/
                        formatter: function (val) { return val.split(" | ").join("\n"); },
                        visualMap: {
                            show: false,
                            min: 80,
                            max: 600,
                            inRange: {
                                colorLightness: [0, 1]
                            }
                        },
                        series: [
                            {
                                name: '楼宇详情',
                                type: 'pie',
                                radius: '50%',
                                center: ['50%', '50%'],
                                data: data,
                                roseType: 'radius',
                                label: {
                                    normal: {
                                        textStyle: {
                                            color: 'rgba(255, 233, 255, 0.8)'
                                        }
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        lineStyle: {
                                            color: 'rgba(255, 255, 255, 0.3)'
                                        },
                                        smooth: 0.2,
                                        length: 10,
                                        length2: 20
                                    }
                                },
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: true,
                                            formatter: function (val) {
                                                return val.name.split(" | ").join("\n");
                                            }
                                        },
                                        shadowBlur: 200,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },

                                animationType: 'scale',
                                animationEasing: 'elasticOut',
                                animationDelay: function (idx) {
                                    return Math.random() * 200;
                                }
                            }
                        ]
                    }
                    eChart.setOption(option, true);

                } else {
                    var error = '<p class="z-t-a-c">' + res.msg + '</p>'
                    chartPieBox.innerHTML = error;
                }
            }
        })

    },
    getData: function (data) {
        var arr = [],
            arrRent = [],
            arrUnrent = [],
            arrExpire = [];

        //console.log(data)
        if (data.expire.length < 1 && data.rent.length < 1 && data.un_rent.length < 1) {
            arr.push({ value: 0, name: "暂无房源信息" })
            return arr;
        }
        for (var i = 0, tmp, len = data.rent.length; i < len; i++) {
            //arr.push({value:data.rent[i].sum,name:data.rent[i].name+"出租" })
            tmp = (data.rent[i].sum != 0 && data.sum_rent != 0) ? (data.rent[i].sum / data.sum_rent).toFixed(2) * 100 + "%" : "0";
            arrRent.push(data.rent[i].name + "已出租：" + tmp);
        }


        for (var i = 0, tmp, len = data.un_rent.length; i < len; i++) {
            //arr.push({value:data.un_rent[i].sum,name:"未出租："+data.rent[i].name})
            tmp = (data.un_rent[i].sum != 0 && data.sum_un_rent != 0) ? (data.un_rent[i].sum / data.sum_un_rent).toFixed(2) * 100 + "%" : "0";
            arrUnrent.push(data.un_rent[i].name + "未出租：" + tmp);
        }
        for (var i = 0, tmp, len = data.expire.length; i < len; i++) {
            //arr.push({value:data.expire[i].sum,name:"今日过期："+data.rent[i].name})
            tmp = (data.expire[i].sum != 0 && data.sum_expire != 0) ? (data.expire[i].sum / data.sum_expire).toFixed(2) * 100 + "%" : "0";
            arrExpire.push(data.expire[i].name + "今日到期：" + tmp);
        }
        if (data.rent.length > 0) arr.push({ value: data.sum_rent, name: arrRent.join(" | ") });
        if (data.un_rent.length > 0) arr.push({ value: data.sum_un_rent, name: arrUnrent.join(" | ") });
        if (data.expire.length > 0) arr.push({ value: data.sum_expire, name: arrExpire.join(" | ") });

        //console.log(arr)
        return arr;
    },
    loadChartBar: function () {
        var _this = this,
            chartBarBox = document.getElementById('chartBarBox'),
            eChartBar = Echart.init(chartBarBox),
            option = null;
        Ajax("/r/UserCenter_moneyStatistics", {
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 200) {
                    var dataa = [
                        {
                            "building_id": 85,
                            "name": "金福大厦",
                            "pay_money": 127996.5,
                            "pay_count": 17,
                            "un_pay_money": 132515.7,
                            "un_pay_count": 12
                        },
                        {
                            "building_id": 93,
                            "name": "雷耀大厦",
                            "pay_money": 365790.43,
                            "pay_count": 49,
                            "un_pay_money": 81881.6,
                            "un_pay_count": 12
                        }
                    ];
                    var res_data = res.data;
                    var data = _this.getChartBarData(dataa);
                    option = {
                        title: {
                            text: '收入统计',
                            left: 'center',
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                            }
                        },
                        legend: {
                            data: ['已收金额（元）', '未收金额（元）', '已收租户（户）', '未收租户（户）', '总收入（元）']
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: 'value'
                            }
                        ],
                        yAxis: [
                            {
                                type: 'category',
                                data: data.buildingNameData
                            }
                        ],
                        series: [
                            {
                                name: '已收金额（元）',
                                type: 'bar',
                                stack: '已收金额',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        textStyle: {
                                            color: '#233'
                                        }
                                    }
                                },
                                data: data.payMoneyData
                            },
                            {
                                name: '未收金额（元）',
                                type: 'bar',
                                stack: '未收金额',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        textStyle: {
                                            color: '#233'
                                        }
                                    }
                                },
                                data: data.unPayMoneyData
                            },
                            {
                                name: '已收租户（户）',
                                type: 'bar',
                                stack: '已收租户',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        textStyle: {
                                            color: '#233'
                                        }
                                    }
                                },
                                data: data.payCntData
                            },
                            {
                                name: '未收租户（户）',
                                type: 'bar',
                                stack: '未收租户',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        textStyle: {
                                            color: '#233'
                                        }
                                    }
                                },
                                data: data.unPayCntData
                            },
                            {
                                name: '总收入（元）',
                                type: 'bar',
                                stack: '总收入',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        textStyle: {
                                            color: '#233'
                                        }
                                    }
                                },
                                data: data.totalMoneyData
                            },

                        ]
                    };
                    eChartBar.setOption(option, true);
                    eChartBar.on("click", function (params) {
                        var name = params.name;
                        console.log(params);
                    })
                } else {
                    
                }
            }
        })
    },
    getChartBarData: function (data) {
        var payCntArr = [],
            payMoneyArr = [],
            unPayCntArr = [],
            unPayMoneyArr = [],
            buildingNameArr = [],
            totalMoneyArr = [];
        for (var i = 0, len = data.length; i < len; i++) {
            payCntArr.push(data[i].pay_count);
            payMoneyArr.push(data[i].pay_money);
            unPayCntArr.push(data[i].un_pay_count);
            unPayMoneyArr.push(data[i].un_pay_money);
            totalMoneyArr.push((data[i].pay_money + data[i].un_pay_money).toFixed(2));
            buildingNameArr.push(data[i].name);
        }
        return arr = {
            payCntData: payCntArr,
            payMoneyData: payMoneyArr,
            unPayCntData: unPayCntArr,
            unPayMoneyData: unPayMoneyArr,
            buildingNameData: buildingNameArr,
            totalMoneyData: totalMoneyArr
        }


    }
});
$(function () {
    new Main();
})
